<template>
  <div class="p-4">
    <div class="flex justify-between items-center mb-4">
      <h1 class="text-xl font-bold">工件列表</h1>
      <UButton icon="i-heroicons-plus" label="新增工件" @click="showAddDialog = true" />
    </div>

    <!-- 车间筛选 -->
    <div class="mb-4">
      <USelect
        v-model="selectedGroup"
        :options="groups"
        option-label="name"
        option-value="id"
        placeholder="选择车间"
        clearable
        class="w-48"
      />
    </div>

    <!-- 工件列表 -->
    <UCard>
      <UTable
        :columns="columns"
        :rows="filteredWorkItems"
        :loading="loading"
        :empty-state="{ icon: 'i-heroicons-document-text', text: '暂无数据' }"
      >
        <template #price-cell="{ row }">
          <div v-for="(price, groupId) in row.groupPrices" :key="groupId">
            {{ getGroupName(groupId) }}: ¥{{ price }}
          </div>
        </template>

        <template #actions-cell="{ row }">
          <UButton
            color="gray"
            variant="ghost"
            icon="i-heroicons-pencil-square"
            :label="'编辑'"
            @click="handleEdit(row)"
          />
          <UButton
            color="red"
            variant="ghost"
            icon="i-heroicons-trash"
            :label="'删除'"
            @click="handleDelete(row)"
          />
        </template>
      </UTable>
    </UCard>

    <!-- 新增/编辑对话框 -->
    <UModal v-model="showAddDialog">
      <UCard>
        <template #header>
          <div class="text-xl font-bold">{{ isEditing ? '编辑工件' : '新增工件' }}</div>
        </template>
        <div class="space-y-4">
          <UFormGroup label="工件名称">
            <UInput v-model="form.name" />
          </UFormGroup>
          <UFormGroup label="工件描述">
            <UTextarea v-model="form.description" />
          </UFormGroup>
          <UFormGroup label="车间单价">
            <div v-for="group in groups" :key="group.id" class="flex items-center gap-2">
              <UCheckbox v-model="form.selectedGroups" :value="group.id" :label="group.name" />
              <UInput
                v-if="form.selectedGroups.includes(group.id)"
                v-model="form.groupPrices[group.id]"
                type="number"
                placeholder="输入单价"
              />
            </div>
          </UFormGroup>
        </div>
        <template #footer>
          <div class="flex justify-end gap-2">
            <UButton label="取消" variant="ghost" @click="showAddDialog = false" />
            <UButton label="确定" color="primary" @click="handleSubmit" />
          </div>
        </template>
      </UCard>
    </UModal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'

interface WorkItem {
  id: number
  name: string
  description: string | null
  groupPrices: Record<string, number>
  createTime: string
  updateTime: string
}

interface Group {
  id: number
  name: string
  description: string | null
  type: number
}

// 表格列定义
const columns = [
  { key: 'id', label: '编号' },
  { key: 'name', label: '名称' },
  { key: 'description', label: '描述' },
  { key: 'price', label: '车间单价' },
  { key: 'actions', label: '操作' }
]

// 状态管理
const loading = ref(false)
const workItems = ref<WorkItem[]>([])
const groups = ref<Group[]>([])
const selectedGroup = ref<number | null>(null)
const showAddDialog = ref(false)
const isEditing = ref(false)

// 表单状态
const form = reactive({
  id: null as number | null,
  name: '',
  description: '',
  selectedGroups: [] as number[],
  groupPrices: {} as Record<string, number>
})

// 获取工件列表
const fetchWorkItems = async () => {
  loading.value = true
  try {
    const { data: response } = await useFetch('/api/work-items')
    workItems.value = response.value?.data || []
  } catch (error) {
    console.error('获取工件列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取车间列表
const fetchGroups = async () => {
  try {
    const { data: response } = await useFetch('/api/groups')
    groups.value = response.value?.data || []
  } catch (error) {
    console.error('获取车间列表失败:', error)
  }
}

// 根据车间ID获取车间名称
const getGroupName = (groupId: string | number) => {
  const group = groups.value.find(g => g.id === (typeof groupId === 'string' ? parseInt(groupId) : groupId))
  return group?.name || '未知车间'
}

// 根据选中的车间筛选工件
const filteredWorkItems = computed(() => {
  if (!selectedGroup.value) return workItems.value
  return workItems.value.filter(item => 
    Object.keys(item.groupPrices).includes(selectedGroup.value.toString())
  )
})

// 处理编辑
const handleEdit = (row: WorkItem) => {
  isEditing.value = true
  form.id = row.id
  form.name = row.name
  form.description = row.description || ''
  form.selectedGroups = Object.keys(row.groupPrices).map(Number)
  form.groupPrices = { ...row.groupPrices }
  showAddDialog.value = true
}

// 处理删除
const handleDelete = async (row: WorkItem) => {
  if (!confirm('确定要删除该工件吗？')) return
  try {
    await $fetch(`/api/work-items/${row.id}`, { method: 'DELETE' })
    await fetchWorkItems()
  } catch (error) {
    console.error('删除工件失败:', error)
  }
}

// 处理提交
const handleSubmit = async () => {
  try {
    const payload = {
      name: form.name,
      description: form.description || null,
      groupPrices: form.groupPrices
    }

    if (isEditing.value && form.id) {
      await $fetch(`/api/work-items/${form.id}`, {
        method: 'PUT',
        body: payload
      })
    } else {
      await $fetch('/api/work-items', {
        method: 'POST',
        body: payload
      })
    }

    showAddDialog.value = false
    await fetchWorkItems()
    resetForm()
  } catch (error) {
    console.error('保存工件失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.name = ''
  form.description = ''
  form.selectedGroups = []
  form.groupPrices = {}
  isEditing.value = false
}

// 页面加载时获取数据
onMounted(() => {
  fetchWorkItems()
  fetchGroups()
})
</script> 